package com.yh.manage.course.service;

import com.alibaba.fastjson.JSON;
import com.lxw.framework.domain.cms.CmsPage;
import com.lxw.framework.domain.cms.response.CmsPageResult;
import com.lxw.framework.domain.cms.response.CoursePreviewResult;
import com.lxw.framework.domain.course.CourseBase;
import com.lxw.framework.domain.course.CourseMarket;
import com.lxw.framework.domain.course.CoursePic;
import com.lxw.framework.domain.course.CoursePub;
import com.lxw.framework.domain.course.ext.CourseView;
import com.lxw.framework.domain.course.ext.TeachplanNode;
import com.lxw.framework.domain.course.response.CourseCode;
import com.lxw.framework.exception.CastException;
import com.lxw.framework.model.response.CommonCode;
import com.lxw.framework.model.response.QueryResponseResult;
import com.lxw.framework.model.response.ResponseResult;
import com.yh.manage.course.client.CmsPageClient;
import com.yh.manage.course.dao.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Optional;

@Service
public class CourseService {

    @Resource
    private CmsPageClient cmsPageClient;

    @Resource
    private TeachplanMapper teachplanMapper;

    @Resource
    private CoursePicRepository coursePicRepository;

    @Autowired
    private CourseBaseRepository courseBaseRepository;

    @Autowired
    private CourseMarketRepository courseMarketRepository;

    @Autowired
    private CoursePubRepository coursePubRepository;

    @Value("${course-publish.siteId}")
    private String siteId;

    @Value("${course-publish.templateId}")
    private String templateId;

    @Value("${course-publish.previewUrl}")
    private String previewUrl;

    @Value("${course-publish.pageWebPath}")
    private String pageWebPath;

    @Value("${course-publish.pagePhysicalPath}")
    private String pagePhysicalPath;

    @Value("${course-publish.dataUrlPre}")
    private String dataUrlPre;

    public QueryResponseResult findCmsPageList(Integer page, Integer size) {
        //fastJson会把json串转换为QueryResponseResult
        QueryResponseResult result = cmsPageClient.findCmsPagesByPage(page, size);
        return result;
    }

    public CourseView findCourseById(String id) {
        if (StringUtils.isEmpty(id)) {
            CastException.cast(CommonCode.VALIDATA);
        }
        //查询课程基本信息
        Optional<CourseBase> courseBaseOptional = courseBaseRepository.findById(id);
        if (!courseBaseOptional.isPresent()) {
            CastException.cast(CommonCode.VALIDATA);
        }
        CourseBase courseBase = courseBaseOptional.get();
        CourseView courseView = new CourseView();
        courseView.setCourseBase(courseBase);

        Optional<CoursePic> coursePicOptional = coursePicRepository.findById(id);
      /*  if (coursePicOptional.isPresent()) {
            CastException.cast(CommonCode.VALIDATA);
        }*/
        //CoursePic coursePic = coursePicOptional.get();
        CoursePic coursePic = coursePicOptional.orElse(null);
        courseView.setCoursePic(coursePic);

        Optional<CourseMarket> courseMarketOptional = courseMarketRepository.findById(id);
        CourseMarket courseMarket = courseMarketOptional.orElse(null);
        courseView.setCourseMarket(courseMarket);

        TeachplanNode teachplanNode = teachplanMapper.selectList(id);
        courseView.setTeachplanNode(teachplanNode);
        return courseView;
    }

    public CoursePreviewResult preview(String id) {

        if(StringUtils.isEmpty(id)){
            CastException.cast(CommonCode.VALIDATA);
        }

        Optional<CourseBase> courseBaseOptional = courseBaseRepository.findById(id);
        if(!courseBaseOptional.isPresent()){
            CastException.cast(CourseCode.COURSE_PUBLISH_COURSEIDISNULL);
        }
        CourseBase courseBase = courseBaseOptional.get();

        //组装CmsPage对象
        //CmsPage cmsPage = this.doneCmsPage(id);
        CmsPage cmsPage = this.doneCmsPage(courseBase);
        //远程调用cms服务
        CmsPageResult cmsPageResult = cmsPageClient.saveCmsPage(cmsPage);
        if(!cmsPageResult.isSuccess()){
            CastException.cast(CourseCode.COURSE_PUBLISH_VIEWERROR);
        }
        CmsPage cmsPageDb = cmsPageResult.getCmsPage();

        //拼装预览Url
        String previewUrlPath = this.previewUrl+cmsPageDb.getPageId();

        return new CoursePreviewResult(CommonCode.SUCCESS,previewUrlPath);

    }

    //组装CmsPage对象
    /*private CmsPage doneCmsPage(String id){*/
/*
        if(StringUtils.isEmpty(id)){
            CastException.cast(CommonCode.VALIDATA);
        }

        Optional<CourseBase> courseBaseOptional = courseBaseRepository.findById(id);
        if(!courseBaseOptional.isPresent()){
            CastException.cast(CourseCode.COURSE_PUBLISH_COURSEIDISNULL);
        }
        CourseBase courseBase = courseBaseOptional.get();*/
    private CmsPage doneCmsPage(CourseBase courseBase){
        CmsPage cmsPage = new CmsPage();
        cmsPage.setTemplateId(templateId);
        cmsPage.setPageAliase(courseBase.getName());
        cmsPage.setDataUrl(dataUrlPre+courseBase.getId());
        cmsPage.setPageWebPath(pageWebPath);
        cmsPage.setPagePhysicalPath(pagePhysicalPath);
        cmsPage.setPageName(courseBase.getId()+".html");
        cmsPage.setPageCreateTime(new Date());
        cmsPage.setSiteId(siteId);
        return cmsPage;
    }

    public ResponseResult post(String id) {

        if(StringUtils.isEmpty(id)){
            CastException.cast(CommonCode.VALIDATA);
        }

        Optional<CourseBase> courseBaseOptional = courseBaseRepository.findById(id);
        if(!courseBaseOptional.isPresent()){
            CastException.cast(CourseCode.COURSE_PUBLISH_COURSEIDISNULL);
        }
        CourseBase courseBase = courseBaseOptional.get();

        //组装cmsPage对象
        //CmsPage cmsPage = this.doneCmsPage(id);
        CmsPage cmsPage = this.doneCmsPage(courseBase);
        //远程调用cms服务，发布课程详情页面
        ResponseResult responseResult = cmsPageClient.postPageQuick(cmsPage);
        //更新课程状态为已发布
        if(responseResult.isSuccess()){
//            Optional<CourseBase> courseBaseOptional = courseBaseRepository.findById(id);
//            CourseBase courseBase = courseBaseOptional.orElse(null);
            courseBase.setStatus("202002");
            courseBaseRepository.save(courseBase);
            //像课程发布表course_pub中存放一条记录
            CoursePub coursePub = new CoursePub();
            BeanUtils.copyProperties(courseBase,coursePub);

            Optional<CourseMarket> courseMarketOptional = courseMarketRepository.findById(id);
            CourseMarket courseMarket = courseMarketOptional.orElse(null);
            BeanUtils.copyProperties(courseMarket,coursePub);

            Optional<CoursePic> coursePicOptional = coursePicRepository.findById(id);
            CoursePic coursePic = coursePicOptional.orElse(null);
            BeanUtils.copyProperties(coursePic,coursePub);

            TeachplanNode teachplanNode = teachplanMapper.selectList(id);
            coursePub.setTeachplan(JSON.toJSONString(teachplanNode));
            coursePub.setTimestamp(new Date());
            coursePubRepository.save(coursePub);
        }
        return responseResult;
    }
}
